/**
 *
 * @param dataList
 * @param idField
 * @param parentIdField
 * @param childrenField
 * @param isSetHasChildren element-plus，如果不是异步获取子节点数据，不要设置hasChildren，否则在页面上展示不出来子节点数据
 * @returns {*|Array|*[]}
 */
export function handleTree(dataList, idField = "id", parentIdField = "parentId", childrenField = "children", isSetHasChildren = false) {

    if (!dataList) {
        return dataList;
    }

    if (!(dataList instanceof Array)) {
        throw new Error("只支持数组类型")
    }

    if (dataList.length <= 0) {
        return dataList;
    }

    let map = new Map();
    const result = [];

    dataList.forEach(data => {
        if (!data[idField]) {
            throw new Error(`必须要有${idField}字段`)
        }
        map.set(data[idField], data)
        data[childrenField] = data[childrenField] || []
        if (isSetHasChildren) {
            data["hasChildren"] = data[childrenField].length > 0
        }
    })

    dataList.forEach(data => {
        let parent = map.get(data[parentIdField])
        if (parent) {
            parent[childrenField].push(data)
            if (isSetHasChildren && !parent["hasChildren"]) {
                parent["hasChildren"] = parent[childrenField].length > 0
            }
        } else {
            result.push(data)
        }
    })

    return result;


}
